<template>
	<view class="container">
		<view class="left-bottom-sign"></view>
		<!-- <view class="back-btn yticon icon-zuojiantou-up" @click="navBack"></view> -->
		<view class="right-top-sign">

		</view>

		<view class="wrapper">

			<view class="left-top-sign">REGISTER</view>
			<view class="welcome">
				欢迎使用{{weChatSetting.wechatAppTitle}}
			</view>
			<view class="wrapper">
				<view class="application-logo">
					<image :src="weChatSetting.wechatAppLogo" mode="aspectFill"></image>
				</view>
				<view class="application-name">
					{{weChatSetting.wechatAppTitle}}
				</view>
			</view>
			<!-- #ifdef MP-WEIXIN -->
			<button class="confirm-btn" @click="getuserinfo">用户微信登录</button>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<button class="confirm-btn">公众号授权中</button>
			<!-- #endif -->
			<view></view>

		</view>
	</view>

</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	// #ifdef H5 || APP-PLUS
	const wx = require('weixin-js-sdk');
	// #endif

	export default {
		data() {
			return {
				mobile: '',
				password: '',
				logining: false,
				to: '',
				wechatUserInfo: {},
				iskeeplive: true,
				current: '',
				message: '',
				communityCode: this.$api.request.communityCode,
				appId: this.$api.request.appId,
				code: '', //用户的code
				loginRes: {
					"header": {
						"requestId": "1837c75b1ba13b6a7958a6d774418490",
						"timeStamp": "1638884608956",
						"applicationId": "b2b2c-mobile",
						"ip": "0.0.0.0",
						"tokenId": "VSsAppbTmP45VabC3hkoVXW3mVfk3sBh"
					},
					"body": {
						"status": {
							"statusCode": "0"
						},
						"data": {
							"createBy": "Consumer",
							"updateBy": "Consumer",
							"openIdOfc": "ojYNns08mb89Bf-EAYcMtw5Erg44",
							"directUserCount": 0,
							"teamUserCount": 0,
							"productUnit": 0,
							"signDateNum": 0,
							"productPoint": 0,
							"total": 0,
							"totalAssignPoint": 0,
							"totalOrder": 0,
							"totalL1": 0,
							"startIndex": 0,
							"pageSize": 0,
							"id": "1194",
							"userCount": 0,
							"userUuid": "8a57d8827e2ee567017e2f1e1af71a5f",
							"photoUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eqIB4vWeic6qQmianEDzMa3ia925UbwIM6lz3dkAUbHXg6OhH2cslJia1btv3QVgWhNqXwHKGcRib7Y0AQ/132",
							"failCount": 0,
							"name": "幕月星烁",
							"sex": "未知",
							"createDate": "2021-11-10 09:58:24",
							"registerDate": "2021-11-10",
							"successCount": 0,
							"couponCount": 0,
							"couponOrderPoint": 0,
							"orderPoint": 0,
							"rankingTotalPoint": 0,
							"ownerInfo": {
								"name": null,
								"sex": null,
								"telNo": '19828635464',
								"ownerId": null,
								"attribute": "NONE"
							},
							"merchantAddress": "",
							"active": true,
							"performanceAmount": 0,
							"performanceAward": 0,
							"availablePoint": 0,
							"supervisorL1PersonalPhone": "",
							"supervisorL1Name": "",
							"supervisorL2Name": "",
							"supervisorL3Name": "",
							"userLevelName": "",
							"inventoryBalance": 0,
							"merchant": false,
							"availableBalance": 0,
							"ledgerBalance": 0,
							"profitWelfareReceived": false,
							"notificationEnabled": false,
							"locked": false
						}
					}
				}
			}
		},
		onLoad(options) {
			// #ifdef MP
			//微信浏览器
			if (this.isWexinBrowser()) {
				let that = this;
				this.code = this.getUrlCode().code
				let localCode = uni.getStorageSync('code')
				console.log('this.code' + this.code + '__' + localCode)
				if (this.code && this.code != localCode) {
					var requestData = {
						verifyType: 'MP',
						code: this.code,
						communityCode: this.communityCode
					};
					this.$api.request.login(requestData, loginRes => {
						if (loginRes.body.status.statusCode === '0') {
							var tokenId = loginRes.header.tokenId;
							uni.setStorageSync('userToken', tokenId);
							that.login(loginRes.body.data); //将用户信息
							console.log('this.code' + this.code)
							uni.setStorageSync("code", this.code)
							uni.setStorageSync("appId", this.appId)
							uni.reLaunch({
								url: '/pages/index/index'
							})
						} else {
							that.loginRedirect();
						}
					})
				} else {
					let uri = encodeURIComponent(window.location.href);
					let authURL = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
						this.appId +
						// '&redirect_uri=' + 'https://cdjjyl.com.cn/SmartServicePlatformAdmin' +
						'&redirect_uri=' + uri +
						'&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect';
					window.location.href = authURL;
					return
				}
			} else {
				uni.showModal({
					title: '提示',
					showCancel: false,
					content: '请在微信客户端打开链接',
					success: res => {
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}
				});

			}
			// #endif
			// #ifdef H5
			setTimeout(() => {
				if (this.loginRes.body.status.statusCode === '0') {
					var tokenId = this.loginRes.header.tokenId;
					uni.setStorageSync('userToken', tokenId);
					this.login(this.loginRes.body.data); //将用户信息
					console.log('this.code' + this.code)
					uni.setStorageSync("code", this.code)
					uni.setStorageSync("appId", this.appId)
					uni.reLaunch({
						url: '/pages/index/index'
					})
				} else {
					this.loginRedirect();
				}
			}, 2000);
		
			// #endif
		},
		onShow() {
			// this.getWeChatSetting()
		},
		computed: {
			...mapState(['weChatSetting', 'userInfo', 'hasLogin'])
		},
		methods: {
			...mapMutations(['login', 'clearFootPrint', 'updateWeCahtSetting']),
			isWexinBrowser() {
				var ua = navigator.userAgent.toLowerCase();
				if (ua.match(/MicroMessenger/i) == "micromessenger") {
					return true;
				} else {
					return false;
				}
			},
			getWeChatSetting() {
				let params = {
					"appId": this.appId
				}
				//获取应用全局设置
				this.$api.request.getWeChatSettingInfo(params, res => {
					if (res.body.status.statusCode === '0') {
						this.updateWeCahtSetting(res.body.data.weChatSetting); //将全局设置保存起来
					} else {
						console.log('获取微信小程序设置信息失败');
					}
				});
			},
			getUrlCode() { // 截取url中的code方法
				var url = location.search
				var theRequest = new Object()
				if (url.indexOf("?") != -1) {
					var str = url.substr(1)
					var strs = str.split("&")
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
					}
				}
				return theRequest
			},

			//公众号
			getUserInfoCommon() {
				// #ifdef H5
				if (this.isWexinBrowser()) {
					let uri = encodeURIComponent(window.location.href);
					console.log('wechatAppIdOfficialAccount' + '')
					let authURL = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
						this.appId +
						// '&redirect_uri=' + 'https://cdjjyl.com.cn/SmartServicePlatformAdmin' +
						'&redirect_uri=' + uri +
						'&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect';
					window.location.href = authURL;
					console.log('地址' + 'authURL：' + authURL)
					return
				}
				// #endif

			},

			getUrlCode() { // 截取url中的code方法
				var url = location.search
				this.winUrl = url
				var theRequest = new Object()
				if (url.indexOf("?") != -1) {
					var str = url.substr(1)
					var strs = str.split("&")
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
					}
				}
				return theRequest
			},
			//微信小程序用户授权
			getuserinfo() {
				let that = this;
				wx.getUserProfile({
					desc: '请求获取微信信息',
					success: function(res) {

					},
					complete: (res) => {
						console.log(res)
						var msg = res.errMsg
						var index = msg.indexOf('ok')
						if (index == -1) {
							// 拒绝授权
							uni.redirectTo({
								url: '/pages/index/index'
							})
							that.$api.msg("您已拒绝授权")
						} else {
							that.wechatUserInfo = res.userInfo;
							uni.login({
								provider: 'weixin',
								success: function(res) {
									that.wechatUserInfo.code = res.code;
									var requestData = {
										verifyType: 'WECHAT',
										appId: that.appId
									};
									that.populateWechatUserInfo(requestData);
									that.clearFootPrint();
									that.$api.request.login(requestData, loginRes => {
										if (loginRes.body.status.statusCode ===
											'0') {
											var tokenId = loginRes.header.tokenId;
											uni.setStorageSync('userToken',
												tokenId);
											that.login(loginRes.body.data); //将用户信息
											uni.reLaunch({
												url: '/pages/index/index'
											})
										} else {
											that.loginRedirect();
										}
									})
								}
							});
						}
					}
				});


			},
			loginmerchant() {
				uni.navigateTo({
					// 此处的链接为小程序上面新建的webview页面路径，参数url为要跳转外链的地址
					url: "/pages/public/merchantLogin"
				});
			},
			loginRedirect() {
				uni.reLaunch({
					url: '/pages/index/user'
				})
			},
			populateWechatUserInfo(requestData) {
				requestData.code = this.wechatUserInfo.code;
				requestData.name = this.wechatUserInfo.nickName;
				requestData.photoUrl = this.wechatUserInfo.avatarUrl;
				let sex = '未知';
				if (this.wechatUserInfo.gender === 1)
					sex = '男';
				else if (this.wechatUserInfo.gender === 2)
					sex = '女';
				requestData.sex = sex;
			},
			inputChange(e) {
				console.log("inputChange:" + e.detail.value);
				const key = e.currentTarget.dataset.key;
				this[key] = e.detail.value;
			},
			navBack() {
				uni.navigateBack();
			},
			toRegister() {
				uni.navigateTo({
					url: '/pages/public/register?to=' + escape(this.to)
				})
			},
			toForgetPassword() {
				uni.navigateTo({
					url: '/pages/public/forgetPassword'
				})
			},
			toLogin() {
				this.logining = true;
				const {
					mobile,
					password
				} = this;
				var isFormValid = true;
				if (!this.$api.util.validateMobileNo(mobile)) {
					this.$api.msg('手机号码格式错误');
					isFormValid = false;
				} else if (!this.$api.util.validatePassword(password)) {
					this.$api.msg('密码为8-20位字母数字下划线组合');
					isFormValid = false;
				}
				if (!isFormValid) {
					this.logining = false;
					return;
				}

				if (this.iskeeplive) { //是否保持登录，下次自动记住密码
					uni.setStorage({
						key: 'mobile',
						data: this.mobile,
						success: function() {
							console.log('mobile is success');
						}
					});
					uni.setStorage({
						key: 'password',
						data: this.password,
						success: function() {
							console.log('password is success');
						}
					});
				} else {
					uni.setStorage({
						key: 'mobile',
						data: '',
						success: function() {
							console.log('mobile is clear');
						}
					});
					uni.setStorage({
						key: 'password',
						data: '',
						success: function() {
							console.log('password  is clear');
						}
					});
				}

				this.$api.request.login({
					verifyType: 'PASSWORD',
					personalPhone: mobile,
					personalPhoneCountryCode: '86',
					password: password
				}, loginRes => {
					if (loginRes.body.status.statusCode === '0') {
						var tokenId = loginRes.header.tokenId;
						uni.setStorageSync('userToken', tokenId);
						this.login(loginRes.body.data); //将用户信息保存起来
						if (this.to) {
							uni.navigateTo({
								url: this.to
							})
						} else {
							uni.navigateTo({
								url: '/package_mall/pages/user/user'
							})
						}
					} else {
						this.$api.msg(loginRes.body.status.errorDesc);
						this.logining = false;
					}
				});
			},

			radioChange: function(evt) {
				console.log("radioChange" + evt.target.value);
				if (evt.target.value.length > 0) {
					if ('保持登录' === evt.target.value[0]) {
						this.iskeeplive = true;
					}
				} else {
					this.iskeeplive = false;
				}

			}
		},

	}
</script>

<style lang='scss'>
	page {
		background: #fff;
	}

	.container {
		padding-top: 75upx;
		position: relative;
		width: 100vw;
		height: 100vh;
		overflow: hidden;
		background: #fff;
	}

	.icon {

		width: 72upx;
		height: 72upx;
		margin-right: 12upx;
		animation: load 1.2s cubic-bezier(.37, 1.08, .7, .74) infinite;
	}

	.img1 {
		position: relative;
	}

	.img1 img {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		margin: auto;
	}

	.wrapper {
		position: relative;
		z-index: 90;
		/* background: #fff; */
	}

	.back-btn {
		position: absolute;
		left: 40upx;
		z-index: 9999;
		padding-top: var(--status-bar-height);
		top: 40upx;
		font-size: 40upx;
		color: $font-color-dark;
	}

	.application-logo {
		text-align: center;

		image {
			width: 200upx;
			height: 200upx;
		}
	}

	.application-name {
		margin-top: 20upx;
		text-align: center;
		color: $font-color-base;
	}

	.left-top-sign {
		font-size: 120upx;
		color: $page-color-base;
		position: relative;
		left: -16upx;
	}

	.meichantlogin {
		position: absolute;
		top: 10upx;
		right: 30upx;
		z-index: 90;
	}

	.right-top-sign {
		position: absolute;
		top: 80upx;
		right: -30upx;
		z-index: 89;

		&:before,
		&:after {
			display: block;
			content: "";
			width: 400upx;
			height: 80upx;
			background: #b4f3e2;
		}

		&:before {
			transform: rotate(50deg);
			border-radius: 0 50px 0 0;
		}

		&:after {
			position: absolute;
			right: -198upx;
			top: 0;
			transform: rotate(-50deg);
			border-radius: 50px 0 0 0;
			/* background: pink; */
		}
	}

	.left-bottom-sign {
		position: absolute;
		left: -270upx;
		bottom: -320upx;
		border: 100upx solid #d0d1fd;
		border-radius: 50%;
		padding: 180upx;

	}

	.welcome {
		position: relative;
		text-align: center;
		top: -90upx;
		font-size: 46upx;
		color: #555;
		text-shadow: 1px 0px 1px rgba(0, 0, 0, .3);
	}

	.input-content {
		padding: 0 60upx;
	}

	.input-item {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		justify-content: center;
		padding: 0 30upx;
		background: $page-color-light;
		height: 120upx;
		border-radius: 4px;
		margin-bottom: 50upx;

		&:last-child {
			margin-bottom: 0;
		}

		.tit {
			height: 50upx;
			line-height: 56upx;
			font-size: $font-sm+2upx;
			color: $font-color-base;
		}

		input {
			height: 60upx;
			font-size: $font-base + 2upx;
			color: $font-color-dark;
			width: 100%;
		}
	}

	.confirm-btn {
		width: 630upx;
		height: 76upx;
		line-height: 76upx;
		border-radius: 50px;
		margin-top: 100upx;
		/* background: $uni-color-back; */
		/* background: #64AF93; */
		background: #70C9AE;
		color: #fff;
		font-size: $font-lg;

		&:after {
			border-radius: 100px;
		}
	}

	.confirm-btn1 {
		width: 630upx;
		height: 76upx;
		line-height: 76upx;
		border-radius: 50px;
		margin-top: 20upx;
		/* color: $uni-color-back; */
		color: #70C9AE;
		font-size: $font-lg;

		&:after {
			border-radius: 100px;
		}
	}

	.remenber-section {

		color: $font-color-spec;
		margin-top: 20upx;
	}

	.forget-section {
		font-size: $font-sm+1upx;
		color: $font-color-spec;
		margin-top: 20upx;
	}

	.register-section {
		position: absolute;
		left: 0;
		bottom: 50upx;
		width: 100%;
		font-size: $font-sm+2upx;
		color: $font-color-base;
		text-align: center;

		text {
			color: $font-color-spec;
			margin-left: 10upx;
		}
	}
</style>
